package cn.tedu._07security.config;

import cn.tedu._07security.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)  //激活鉴权
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //在Ioc容器中注册Bean对象，因为鉴权是会调用loadUserByUsername()方法
    @Bean
    public UserDetailsService userDetailsService(){
        return new UserDetailsServiceImpl();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();  //关闭站点伪装攻击

        http
                //1.配置授权的请求规则
                .authorizeRequests()
                    .antMatchers("/api/public/**").permitAll()
                    .anyRequest().authenticated()
                .and()

                //2.配置表单登录
                .formLogin()
                    .defaultSuccessUrl("/index.html")
                    .permitAll()
                .and()

                //3.配置注销登陆
                .logout()
                .permitAll();
    }
    /**
     * 配置一个简单的用户名和密码，user 和 123456
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication()
                .withUser("user")
                .password("{noop}123456")
                .roles("USER")
                .authorities("sys:private:view","sys:private:edit");
    }

}
